6/28/2019

Trust me, I know

Facebook marketing API

  • creat, read, update, and delete custom audiences, images, campaigns, adsets, ads, and related content

Create a Facebook app to get token

  • Make sure you log in your facebook
  • Open https://developers.facebook.com/apps
  • Register as a developer
  • Add a new app
  • Type in a unique display name and provide your email address. Click "Create App ID"
  • Select a Scenario: click "Implement Marketing API"
  • In the sidebar, select "Tools" from the "Marketing API" and generate a token

Here's the video

Authorization

devtools::install_github('daroczig/fbRads')
library(fbRads)

#load token
token = readRDS('token.rds')
#use token to get your account id
accounts = fbad_get_my_ad_accounts(token, version = '3.3')
#get your account id
account = sample(accounts$account_id,1)

# initiate your FB Marketing API
fbad_init(accountid = account, token = token, version= '3.3')
## TRACE [2019-06-24 15:44:55] Initializing connection to account 149182307 via API v3.3

Audience insights from FB

Start targeting

Detailed targeting

Target your audience

  • Number of programmers on Facebook
prog = fbad_get_search(q = 'programming language', type = 'adinterest')
prog %>% arrange(desc(audience_size)) %>% head()
##              id                          name audience_size
## 1 6003030200185          Programming language     394703980
## 2 6003321322341      C (programming language)      79857510
## 3 6003437022731   Java (programming language)      45059180
## 4 6003682002118 Python (programming language)      18326860
## 5 6002979703120   Ruby (programming language)      10948870
## 6 6003696909290 Erlang (programming language)       6411510
##                                                             path
## 1          Interests, Additional Interests, Programming language
## 2      Interests, Additional Interests, C (programming language)
## 3   Interests, Additional Interests, Java (programming language)
## 4 Interests, Additional Interests, Python (programming language)
## 5   Interests, Additional Interests, Ruby (programming language)
## 6 Interests, Additional Interests, Erlang (programming language)
##   description      topic disambiguation_category
## 1          NA       <NA>                    <NA>
## 2          NA       <NA>                    <NA>
## 3          NA Technology                    <NA>
## 4          NA Technology                    <NA>
## 5          NA Technology                    <NA>
## 6          NA       <NA>          Local Business

The size of audience

  • US-based python users
#get ids and names for python users
python = prog %>% slice(4)
#get numbers
fbad_reachestimate(targeting_spec = list(
  geo_locations = list(countries = 'US'),
  flexible_spec = list(
    list(interests = data.frame(
      id = python$id,
      name = python$name))
  )
))$users
## [1] 5400000

The size of audience (Continued)

  • How about US-based R users?
r = prog %>% slice(15)

fbad_reachestimate(targeting_spec = list(
  geo_locations = list(countries = 'US'),
  flexible_spec = list(
    list(interests = data.frame(
      id = r$id,
      name = r$name))
  )
))$users
## [1] 44000

Targeting by demographics

  • Income
income = fbad_get_search(q = 'income', type = 'targetingsearch')[1:4,1:2]
income
##              id                                            name
## 1 6107813554583 Household income: top 25%-50% of ZIP codes (US)
## 2 6107813553183 Household income: top 10%-25% of ZIP codes (US)
## 3 6107813551783     Household income: top 10% of ZIP codes (US)
## 4 6107813079183      Household income: top 5% of ZIP codes (US)

Income function example

fb_income_eg = function(interest_id, interest_name){
  id = c("6107813079183","6107813551783", "6107813553183","6107813554583")
  name = c("Top 5%","Top 10%","Top 10%-25%", "Top 25%-50%")
  
  income = purrr::map(1:length(id),function(i)
    fbad_reachestimate(targeting_spec = list(
      geo_locations = list(countries = 'US'),
      flexible_spec = list(
        list(interests = data.frame(
          id = interest_id,
          name = interest_name
        )),
        list(income = data.frame(
          id = id[i],
          name = name[i]
        ))
      )
    ))$users)
  
  data_frame = as.data.frame(cbind(name, income))
  colnames(data_frame) = c("Income Level", "Count")
  return(data_frame)
}

Get results

income_table = fb_income_eg('6003682002118', 'Python (programming language)')
Income Level Count
Top 5% 210000
Top 10% 390000
Top 10%-25% 350000
Top 25%-50% 390000

Python library

from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adset import AdSet
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<AD_ACCOUNT_ID>'
FacebookAdsApi.init(access_token=access_token)

Python sample code

fields = [
]
params = {
  'name': 'My First AdSet',
  'daily_budget': '10000',
  'bid_amount': '300',
  'billing_event': 'IMPRESSIONS',
  'optimization_goal': 'REACH',
  'campaign_id': '<adCampaignLinkClicksID>',
  'promoted_object': {'page_id':'<pageID>'},
  'targeting': {'geo_locations':{'countries':['US'],'regions':[{'key':'4081'}],
                'cities':[{'key':777934,'radius':10,'distance_unit':'mile'}]},
                'genders':[1],'age_max':24,'age_min':20,
                'publisher_platforms':['facebook','audience_network'],
                'device_platforms':['mobile'],
  'flexible_spec':[{'interests':[{'id':'<adsInterestID>','name':'<adsInterestName>'}]}]},
  'status': 'PAUSED',
}
print AdAccount(id).create_ad_set(
  fields=fields,
  params=params,
)

Next step

  • Once you know who and where you target, you can create a campaign(s)
  • Facebook will put your ads to the specific audience you set

Caveat

  • Human bias leads to data bias
  • Data Privacy

Instagram private API

Other social media API

Thank You!

  • Special thanks to the former developer/data scientist at DKC, Harro Cyranka 👍

  • Instagram, Facebook, Twitter @suminisweird
  • Github, Linkedin @szuminyu